<?php
!function_exists('adminmsg') && exit('Forbidden');
$basename="$admin_file?adminjob=sendmail";

if(empty($action)){
	include PrintEot('sendmail');exit;
} elseif($action=="send"){
	$_SERVER['REQUEST_METHOD']!='POST' && PostCheck($verify);
	require_once(R_P.'require/sendemail.php');

	InitGP(array('step','by','sendto','subject','atc_content','percount','count'));
	$cache_file = D_P."data/bbscache/".substr($admin_pwd,10,10).".txt";
	if(!$step){
		writeover($cache_file,$atc_content);
	} else{
		$atc_content = readover($cache_file);
	}
	if(empty($subject) || empty($atc_content)){
		adminmsg('sendmsg_empty');
	}
	$subject     = Char_cv($subject);
	$sendmessage = Char_cv($atc_content);
	!$percount && $percount=100;
	empty($step) && $step=1;
	$start = ($step-1)*$percount;
	$limit = "LIMIT $start,$percount";

	if($by==0){
		!$sendto && adminmsg('operate_error');
		is_array($sendto) && $sendto = implode(",",$sendto);
		$sqlwhere = "groupid IN('".str_replace(",","','",$sendto)."')";
		if($step==1){
			$rs=$db->get_one("SELECT count(*) AS count FROM pw_members WHERE $sqlwhere");
			$count=$rs['count'];
		}
	} elseif($by==1){
		require_once(R_P.'require/GetOnlineUser.php');
		$onlineuser = GetOnlineUser();
		$uids='';
		foreach($onlineuser as $key => $value){
			is_numeric($key) && $uids .=  $uids ?  ",$key" : $key;
		}
		$sqlwhere = "uid IN($uids)";
		$count=count($onlineuser);
	} else{
		adminmsg('operate_error');
	}

	$query=$db->query("SELECT username,email FROM pw_members WHERE $sqlwhere $limit");
	while($rt=$db->fetch_array($query)){
		$sendmessage = str_replace('$email',$rt['email'],$atc_content);
		$sendmessage = str_replace('$windid',$rt['username'],$sendmessage);
		sendemail($rt['email'],$subject,$sendmessage,'email_additional');
	}

	$havesend = $step*$percount;
	if($count > $step*$percount){
		$step++;
		$j_url="$basename&action=$action&step=$step&count=$count&sendto=$sendto&present=$present&subject=".rawurlencode($subject)."&by=$by&percount=$percount";
		adminmsg("sendmsg_step",EncodeUrl($j_url),1);
	} else{
		P_unlink($cache_file);
		adminmsg('sendmsg_success');
	}
}
?>